/**
 *
 */
package steven.gui.console;

import java.awt.event.WindowEvent;
import java.awt.im.InputContext;

import javax.swing.JFrame;
import javax.swing.JScrollPane;

import steven.gui.console.shell.ShellConsole;

/**
 * @author steven.lam.t.f
 *
 */
public class ConsoleWindow implements ConsoleController{
	private static final long MINIMUM_REPAINT_INTERVAL = 100;
	private final Object repaintLock = new byte[0];
	private final JFrame frame = new JFrame(ConsoleWindow.class.getSimpleName());
	private final Console console = new ShellConsole(this);
	private final JScrollPane scrollPane = new JScrollPane(this.console);
	private long repaintDelay;

	public ConsoleWindow(){
		this.repaintDelay = ConsoleWindow.MINIMUM_REPAINT_INTERVAL;
		this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.frame.add(this.scrollPane);
		this.frame.setSize(400, 300);
		this.frame.setVisible(true);
		this.scrollPane.getActionMap().setParent(null);
		new Thread(() -> {
			while(true){
				if(ConsoleWindow.this.repaintDelay > 0){
					try{
						Thread.sleep(ConsoleWindow.this.repaintDelay);
					}catch(final InterruptedException e){
					}
				}
				synchronized(ConsoleWindow.this.repaintLock){
					ConsoleWindow.this.console.repaint();
					try{
						ConsoleWindow.this.repaintLock.wait();
					}catch(final InterruptedException e){
					}
				}
			}
		}).start();
		this.console.requestFocus();
		this.console.onCreate();
	}
	@Override
	public void repaint(){
		synchronized(this.repaintLock){
			this.repaintDelay = 0;
			this.repaintLock.notifyAll();
		}
	}
	@Override
	public void terminate(){
		this.frame.dispatchEvent(new WindowEvent(this.frame, WindowEvent.WINDOW_CLOSING));
	}
	public void setSize(final int width, final int height){
		this.frame.setSize(width, height);
	}
}
